<template>
  <el-dialog :title="title" v-model="visible" align-center width="800px" @close="handleClose" :close-on-click-modal="false">
    <el-form :model="formData" label-width="120px" :rules="rules" ref="ruleFormRef" class="formw200" :disabled="formDisable">
      <el-form-item label="规则名称：" prop="rule_name">
        <el-input v-model="formData.rule_name" class="input" placeholder="规则名称" />
      </el-form-item>
      <el-form-item label="优先级：" prop="priority">
        <el-input type="number" style="width: 300px" v-model="formData.priority" @change="(v) => (formData.priority = v.toString().replace(/\.\d+$/, ''))" placeholder="数字越大优先级越高" />
        <span class="ml-4">数字越大优先级越高！</span>
      </el-form-item>

      <div class="plf">
        <SelectPlatformSiteShop
          multiple
          ref="SelectPlatformSiteShopRef"
          :platformMultiple="1"
          :showRule="[true, true, false]"
          v-model:site="formData.site"
          :show-label="true"
          required
          label-width="120px"
          :inline="false"
          v-model:platform="formData.platform_id"
        />
        <div class="btns">
          <el-button type="primary" class="ml-4" @click="checkSite('checkAll')">全选</el-button>
          <el-button type="primary" class="ml-4" @click="checkSite('reverse')">反选</el-button>
          <el-button type="primary" class="ml-4" @click="clearSite" :disabled="formDisable">清空</el-button>
        </div>
      </div>
      <el-form-item label="发货仓库规则：" prop="shipping_method_list">
        <el-radio-group v-model="formData.wms_choose_type">
          <el-radio :label="1" size="large">手动选择仓库</el-radio>
          <el-radio :label="2" size="large">按仓库类型选择</el-radio>
        </el-radio-group>
        <div class="w100">
          <SelectWarehouse multiple collapse-tags v-if="formData.wms_choose_type === 1" style="width: 300px" @change="handleWareSelectChange" v-model="warehouse" />
          <SelectWarehouseType v-else multiple collapse-tags @change="handleWareSelectChange" v-model="warehouseType" style="width: 300px" />
        </div>
        <el-table :data="formData.warehouse" border style="width: 100%; margin-top: 10px">
          <el-table-column prop="warehouse_name" label="仓库名称" width="180" />
          <el-table-column prop="priority" label="优先级" width="180">
            <template #default="{ row, $index }">
              <el-input type="number" @change="(v) => (row.priority = v.toString().replace(/\.\d+$/, ''))" v-model="row.priority" />
            </template>
          </el-table-column>
          <el-table-column prop="wms_attribute_cn" label="仓库类型" />
          <el-table-column label="操作">
            <template #default="{ row, $index }">
              <el-link type="danger" :underline="false" :disabled="formDisable" @click="delTableData('warehouse', $index)">删除 </el-link>
            </template>
          </el-table-column>
        </el-table>

        <el-checkbox v-model="formData.is_verify_inventory" :true-value="1" :false-value="0" size="large">是否验证库存 </el-checkbox>
      </el-form-item>
      <el-form-item label="运输方式：" v-show="formData.shipping.length">
        <div class="box w100">
          <div class="w100" v-for="(item, index) in formData.shipping" :key="index">
            <p>{{ item.warehouse_name }}</p>
            <el-radio-group v-model="item.choose_type" @change="(v) => handleChooseTypeChange(v, index)">
              <el-radio :label="1" size="large">手动选择渠道</el-radio>
              <el-radio :label="2" size="large">按运输规则</el-radio>
            </el-radio-group>
            <div>
              <VXSelect
                v-if="item.choose_type === 1"
                :list="optionsList.optsChannelList.filter((v) => v.warehouse.includes(item.warehouse_id))"
                :formatter="(dtd) => dtd.map((v) => ({ label: v.channel_name, value: v.id }))"
                multiple
                collapse-tags
                clearable
                filterable
                @change="(v) => handleSelectShippingMethod(v, index)"
                v-model="item.shipping_id"
                placeholder="运输方式"
                class="w-[400px] input"
              />
              <div class="flex" style="align-items: center" v-else>
                <span>是否挂号：</span>
                <el-radio-group v-model="item.is_register" @change="() => handleIsRegister(index)" style="width: 120px">
                  <el-radio :label="1" size="large">是</el-radio>
                  <el-radio :label="0" size="large">否</el-radio>
                </el-radio-group>
                <SelectTransportType v-model="formData.shipping_type" @change="(v) => handleShippingType(v, index)" placeholder="请选择运输类型" />
              </div>
            </div>
            <el-table :data="item.children" border style="width: 100%; margin-top: 10px">
              <el-table-column prop="shipping_name" align="center" label="运输方式" width="280" />
              <el-table-column prop="priority" align="center" label="优先级" width="100">
                <template #default="{ row, $index }">
                  <el-input v-model="row.priority" @change="(v) => (row.priority = v.toString().replace(/\.\d+$/, ''))" />
                </template>
              </el-table-column>
              <el-table-column label="操作（清空）" align="center">
                <template #header="{ column, $index }">
                  操作
                  <!-- <el-link type="danger" :underline="false"
                           @click="aaaaa(column, $index)">清空
                  </el-link> -->
                  <el-link type="danger" :underline="false" :disabled="formDisable" @click=";(formData.shipping[index].shipping_id = []), handleSelectShippingMethod([], index)">清空 </el-link>
                </template>
                <template #default="{ row, $index }">
                  <el-link type="danger" :underline="false" :disabled="formDisable" @click="delTableDataForShipping(index, $index)">删除 </el-link>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="运输方式规则：">
        <el-input-number style="width: 200px; text-align: left !important" :controls="false" :precision="2" v-model="formData.limitation_days" placeholder="请输入" />
        <span class="ml-2">天</span>
        <div class="w100 text-[var(--base-text-color)]">注：为空则不校验，如填写10天，则匹配10天内可送达的运输方式！</div>
      </el-form-item>
      <el-divider> 满足以上条件时，执行以下操作 </el-divider>
      <el-form-item label="自动分仓：" class="text-[var(--base-text-color)]">
        <div>1.多仓库可用库存充足，取优先级最高的仓；</div>
        <div>2.多仓库在途库存充足，取优先级最高的仓；</div>
        <div>3.仓库可用和在途库存都不充足，取优先级最高的仓；</div>
        <div>4.如所维护的仓库都不符合条件则取优先级最高的仓；</div>
      </el-form-item>
      <el-form-item label="物流优选：">
        <el-checkbox :label="item.label" v-model="formData.choose_type" v-for="item in optionsList.wms_preferred_choose_type" :key="item.value" :true-value="item.value" :false-value="item.value" />
      </el-form-item>
      <el-form-item label="状态：">
        <el-switch v-model="formData.status" :active-value="1" :inactive-value="2"></el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" v-if="!formDisable" :loading="loadings.submit" @click="submit">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, toRefs } from "vue"
import api from "../api"
import { ElMessage } from "element-plus"
import SelectPlatformSiteShop from "@/components/Selects/SelectPlatformSiteShop/index.vue"
import { apiGetChannel, apiGetOptsChannel, apiGetWarehouseList, overallOptions, tmsOverallOptions } from "@/api/public"
import SelectWarehouse from "@/components/Selects/SelectWarehouse/index.vue"
import SelectWarehouseType from "@/components/Selects/SelectWarehouseType/index.vue"
import { intersection } from "lodash"
import SelectShippingMethod from "@/components/Selects/SelectShippingMethod/index.vue"
import SelectTransportType from "@/components/Selects/SelectTransportType/index.vue"
import { clearObj, deepClone } from "@/utils"

const formTemp = {
  rule_name: "",
  priority: "0",
  platform_id: "",
  site: [],
  shipping: [],
  warehouse: [],
  is_verify_inventory: "0",
  limitation_days: "",
  status: "1",
  wms_choose_type: 1,
}
const aaaaa = (column, $index) => {
  console.log(column, $index)
}
const ruleFormRef = ref()
const warehouse = ref()
const warehouseType = ref()
const mapChannel = ref([])
const optionsList = ref({
  wms_preferred_choose_type: [],
  wms_preferred_status: [],
  mapChannel: [],
  optsChannelList: [],
})
const visible = ref(false)
const SelectPlatformSiteShopRef = ref()
let loadings = reactive({})
// 声明接收参数
const props = defineProps({
  title: {
    type: String,
    default: "新增",
  },
})

const data = reactive({
  formData: deepClone(formTemp),
  isType: false,
})
const { formData, isType } = toRefs(data)
const { title } = toRefs(props)
const emit = defineEmits(["close", "confirm"])
const rules = reactive({
  rule_name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  // priority: [
  //   {required: true, message: '不能为空', trigger: 'change'}
  // ],
  // platform: [
  //   {required: true, message: '不能为空', trigger: 'change'}
  // ],
  // site: [
  //   {required: true, message: '不能为空', trigger: 'change'}
  // ],
  // shipping_method_list: [
  //   {required: true, message: '不能为空', trigger: 'change'}
  // ],
  // warehouse_list: [
  //   {required: true, message: '不能为空', trigger: 'change'}
  // ]
})
//删除表格数据
const delTableData = (key, index) => {
  const row = formData.value.warehouse[index]
  switch (key) {
    case "warehouse":
      formData.value.warehouse.splice(index, 1)
      formData.value.shipping.splice(index, 1)
      const { wms_choose_type } = formData.value
      if (wms_choose_type === 1) {
        const _findIndex = warehouse.value.findIndex((v) => v === row.warehouse_id)
        if (_findIndex > -1) warehouse.value.splice(_findIndex, 1)
      } else {
        const types = [...new Set(formData.value.warehouse.map((v) => v.warehouse_type))]
        warehouseType.value = intersection(types, warehouseType.value)
      }
      break
    default:
      break
  }
}

const delTableDataForShipping = (index, $index) => {
  const row = formData.value.shipping[index]
  const { choose_type, shipping_id, children } = row
  const childShippingId = children[$index].shipping_id
  row.children.splice($index, 1)
  // 清除select选项
  if (choose_type === 1) {
    // 手动选择渠道
    const _findIndex = shipping_id.findIndex((v) => v === childShippingId)
    if (_findIndex > -1) row.shipping_id.splice(_findIndex, 1)
  } else {
    const types = [...new Set(children.map((v) => v.shipping_id))]
    formData.value.shipping_type = intersection(types, formData.value.shipping_type)
  }
}
const formDisable = ref(false)
// 打开弹窗
// const open = (row = {}, disable = false) => {
// disable 订单排程和操作策略  分仓和物流优选查看详情
const open = (row = {}, type, disable = false) => {
  formDisable.value = disable
  if (row.id) {
    isType.value = type == "edit"
    api.detail(row.id).then((res) => {
      const dtd = deepClone(res.data)
      let index = 0
      for (const item of dtd.shipping) {
        const { children } = item
        dtd.shipping[index].shipping_id = [...new Set(children.map((v) => v.shipping_id))]
        index++
      }
      initotpsChannel(dtd.warehouse.map((v) => v.warehouse_id))
      formData.value = dtd
      warehouse.value = formData.value?.warehouse?.map((v) => v.warehouse_id)
      visible.value = true
      setTimeout(() => {
        let keysOpt = Object.fromEntries(optionsList.value.optsChannelList.map((v) => [v.id, v.channel_name]))
        for (let key in formData.value.shipping) {
          let row = formData.value.shipping[key]
          row.children = row.children.filter((v) => keysOpt[v.shipping_id]).map((v) => ({ ...v, shipping_name: keysOpt[v.shipping_id] || v.shipping_name }))

          // row.children = row.children.map((v) => ({ ...v, shipping_name: keysOpt[v.shipping_id] || v.shipping_name }))
        }
      }, 300)
    })
  } else {
    loadings = reactive({})
    formData.value = deepClone(formTemp)
    isType.value = false
    visible.value = true
  }
}
// 关闭弹窗
const close = () => {
  formData.value = deepClone(formTemp)
  warehouse.value = []
  warehouseType.value = []
  // ruleFormRef.value.resetFields()
  visible.value = false
}

const clearSite = () => {
  formData.value.sites = []
}

const checkSite = (type) => {
  SelectPlatformSiteShopRef.value.checkAll("site", type)
}

const handleClose = () => {
  close()
  emit("close")
}

const handleWarehouseRulesTable = () => {}

const initotpsChannel = async (value) => {
  const res1 = await apiGetOptsChannel({ warehouse: value, source_os: "oms" })
  optionsList.value.optsChannelList = res1.data.filter((v) => v.status)
}

const handleWareSelectChange = async (value) => {
  if (!value.length) {
    formData.value.warehouse = []
    warehouseType.value = []
    warehouse.value = []
    formData.value.shipping = []
    return
  }
  const { wms_choose_type } = formData.value
  const postDtd = {}
  if (wms_choose_type === 1) {
    postDtd.warehouse_id = value
  } else {
    postDtd.wms_attribute = value
  }
  const res = await apiGetWarehouseList(postDtd)
  const dtd = res.data.map((v) => ({
    warehouse_id: v.id,
    warehouse_name: v.warehouse_name,
    warehouse_type: v.wms_attribute,
    wms_attribute_cn: v.wms_attribute_cn,
    priority: 1,
  }))
  formData.value.warehouse = dtd
  setShippingData(dtd)
  initotpsChannel(value)
}

const setShippingData = (data) => {
  let old_warehouse_ids = formData.value.shipping.map((v) => v.warehouse_id)
  data.forEach((item) => {
    if (!old_warehouse_ids.includes(item.warehouse_id)) {
      formData.value.shipping.push({
        warehouse_id: item.warehouse_id, // 仓库id
        warehouse_name: item.warehouse_name, // 仓库名称
        warehouse_type: item.wms_attribute, // 仓库类型
        children: [], // 运输方式
        is_register: 0, // 是否挂号
        choose_type: 1, // 选择方式
        shipping_type: "", // 运输方式id
      })
    }
  })
  // formData.value.shipping = data.reduce((pre, cur) => {
  //   pre.push({
  //     warehouse_id: cur.warehouse_id, // 仓库id
  //     warehouse_name: cur.warehouse_name, // 仓库名称
  //     warehouse_type: cur.wms_attribute, // 仓库类型
  //     children: [], // 运输方式
  //     is_register: 0, // 是否挂号
  //     choose_type: 1, // 选择方式
  //     shipping_type: "", // 运输方式id
  //   })
  //   return pre
  // }, [])
}

const handleChooseTypeChange = (value, index) => {
  const row = formData.value.shipping[index]
  row.children = []
  row.shippingMethod = []
  row.shipping_type = []
  // 清空下拉选项
  row.shipping_id = []
  formData.value.shipping_type = []
}

const setShippingChild = async (params, index) => {
  const row = formData.value.shipping[index]
  const res = await apiGetChannel({ ...params, source_os: "oms" })
  row.children = res.data.reduce((pre, cur) => {
    const { logistics_id, id, channel_name } = cur
    pre.push({
      shipping_id: id,
      priority: 1,
      shipping_name: channel_name,
    })
    return pre
  }, [])
}

const handleSelectShippingMethod = async (values, index) => {
  const row = formData.value.shipping[index]
  if (!values.length) {
    return (row.children = [])
  }
  const params = { channel_id: values }
  setShippingChild(params, index)
}

const handleIsRegister = (index) => {
  // formData.value.shipping[index].
}

const handleShippingType = async (value, index) => {
  const row = formData.value.shipping[index]
  if (!value) {
    return (row.children = [])
  }
  const params = {
    transport_type: value,
    is_register: row.is_register,
  }
  setShippingChild(params, index)
}

// const handleChange

// 提交
const submit = () => {
  console.log(formData.value)
  let { validate } = ruleFormRef.value
  validate((valid) => {
    if (valid) {
      let shipping = formData.value.shipping.find((v) => (v.choose_type == 1 && v.shipping_id && v.shipping_id?.length != 0) || (v.choose_type == 2 && v.children && v.children?.length != 0))
      if (!shipping) {
        return ElMessage.warning("至少维护一条运输方式")
      }
      let params = { ...formData.value }
      if (isType.value) {
        // const {warehouse_list, ...obj} = formData.value
        // obj.warehouse_list = []
        // formData.value.shipping_method_list.map(e => {
        //   const {shipping_method, ...ebj} = e
        //   obj.warehouse_list.push(ebj)
        // })

        api
          .update(params, formData.value.id)
          .then((res) => {
            ElMessage({ message: "保存成功！", type: "success" })
            emit("confirm")
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      } else {
        delete params.id
        api
          .create({ ...params })
          .then((res) => {
            ElMessage({ message: "保存成功！", type: "success" })
            emit("confirm")
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      }
    }
  })
}

const initSelectOptions = async () => {
  const res = await overallOptions({
    option: "new",
    params: ["wms_preferred_choose_type", "wms_preferred_status", "mapChannel"],
  })
  const { wms_preferred_choose_type, wms_preferred_status } = res.data
  optionsList.value.wms_preferred_choose_type = wms_preferred_choose_type
  formTemp.choose_type = wms_preferred_choose_type[0].value
  optionsList.value.wms_preferred_status = wms_preferred_status
  optionsList.value.mapChannel = mapChannel
}

onMounted(() => {
  initSelectOptions()
})
defineExpose({ open })
</script>
<style lang="scss" scoped>
.formw200 {
  :deep(.input) {
    width: 300px;
  }
}

.w100 {
  width: 100%;
}

:deep(input::-webkit-outer-spin-button),
:deep(input::-webkit-inner-spin-button) {
  -webkit-appearance: none !important;
}

:deep(.el-input__inner) {
  line-height: 1px !important;
}

.el-radio.el-radio--large {
  height: initial;
}

.box {
  border: 1px solid var(--base-border-color);
  border-radius: 5px;
  padding: 10px;
}

:deep(.sel-platform-site-shop-item) {
  margin-bottom: 18px;
  .el-select {
    width: 300px !important;
  }
}

.plf {
  position: relative;
  .btns {
    position: absolute;
    bottom: 0;
    left: 430px;
  }
}
.input {
  :deep(.el-tag.is-closable) {
    max-width: 180px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
